import pandas as pd
from typing import Dict, List

from interfaces.transformers import IBloodDraw
from interfaces.form_metadata import IFormMetadataProvider
from common.pivot.custom_col_pivot import DataPivotTransformer
from constants import SUBJECT_NUMBER, DATA_FESTIVAL, LINE_NUMBER, BLOOD_DRAW, FormAllConstants


class BloodDrawTransformer(IBloodDraw):
    def __init__(self, default_source_data: str, metadata: IFormMetadataProvider):
        self.default_source_data = default_source_data
        self.metadata = metadata
        self.pivot = DataPivotTransformer(default_source_data)

    def process_blood_draw(self, all_results: Dict[str, pd.DataFrame]) -> None:
        blood_oids: List[str] = self.metadata.get_targets((FormAllConstants.IsBloodDraw, True), FormAllConstants.ModuleOID, True)
        if not blood_oids:
            return
        for oid in blood_oids:
            # 推断值列，保持顺序为 ['PCTPT', 'PCDAT', 'PCTIM']（若存在）
            non_value_cols = {SUBJECT_NUMBER, DATA_FESTIVAL, LINE_NUMBER}
            value_cols = [c for c in ['PCTPT', 'PCDAT', 'PCTIM'] if c in BLOOD_DRAW]
            # 构造通用透视配置
            config = {
                'sheet_name': oid,
                'base_cols': [SUBJECT_NUMBER],
                'merge_keys': [SUBJECT_NUMBER],
                'group_dims': [DATA_FESTIVAL, LINE_NUMBER],
                'value_cols': value_cols,
            }
            try:
                df = self.pivot.perform_pivot(config)
            except Exception:
                continue
            if df is None or df.empty:
                continue
            all_results[oid + "血样采集"] = df